package org.example;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class revcomp {
    private static final byte[] complement = new byte[256];
    private static final int LINE_LENGTH = 80; // 每行显示的字符数

    static {
        // 初始化互补碱基映射表（包含大小写）
        for (int i = 0; i < 256; i++) {
            complement[i] = (byte) i;
        }
        complement['A'] = 'T';
        complement['T'] = 'A';
        complement['C'] = 'G';
        complement['G'] = 'C';
        complement['a'] = 't';
        complement['t'] = 'a';
        complement['c'] = 'g';
        complement['g'] = 'c';
    }

    public static void main(String[] args) throws IOException {
        // 读取 dna.txt 文件内容
        byte[] input = Files.readAllBytes(Paths.get("/Users/huawei/IdeaProjects/java_cases_for_performance/src/main/java/org/example/dna.txt"));

        // 过滤非碱基字符
        byte[] filtered = filterBases(input);

        // 计算反向互补序列
        byte[] result = reverseComplement(filtered);

        // 带换行输出结果
        printWithNewlines(result);
    }

    // 过滤非碱基字符
    private static byte[] filterBases(byte[] input) {
        int count = 0;
        for (byte b : input) {
            if (b == 'A' || b == 'T' || b == 'C' || b == 'G' ||
                    b == 'a' || b == 't' || b == 'c' || b == 'g') {
                count++;
            }
        }

        byte[] filtered = new byte[count];
        int index = 0;
        for (byte b : input) {
            if (b == 'A' || b == 'T' || b == 'C' || b == 'G' ||
                    b == 'a' || b == 't' || b == 'c' || b == 'g') {
                filtered[index++] = b;
            }
        }
        return filtered;
    }

    // 生成反向互补序列
    private static byte[] reverseComplement(byte[] input) {
        int n = input.length;
        byte[] result = new byte[n];

        for (int i = 0; i < n; i++) {
            result[i] = complement[input[n - 1 - i] & 0xFF];
        }

        return result;
    }

    // 带换行输出（每LINE_LENGTH个字符换一行）
    private static void printWithNewlines(byte[] data) throws IOException {
        OutputStream out = System.out;
        int length = data.length;

        for (int i = 0; i < length; i++) {
            out.write(data[i]);
            // 每LINE_LENGTH个字符添加一个换行符（最后一行不额外添加）
            if ((i + 1) % LINE_LENGTH == 0 && i != length - 1) {
                out.write('\n');
            }
        }
        // 最后添加一个换行符，确保输出结束后换行
        out.write('\n');
        out.flush();
    }
}
